import os
import datetime
import random
from django.shortcuts import render
from django.http import JsonResponse
from django.db.models import F
from core.tools.tel_verify import verify_tel
from finance_c2c.local_settings import Config
from core.tools.wx_login_verify import wx_login
from core.wchat.models import WxUserInfo
from core.tools.wx_session import get_wx_session
from apps.sales_man.models import EnterApplyInfo
from apps.sales_man.models import SalesMan, BoundRelation, ApplicantList, Single, IssueContent
from apps.product.models import Product
from apps.order.models import TeamInCome
from core.tools.encryption import md5
from core.tools.paginator import DjangoPaginator
from core.tools.account_password_authentication import authentication


@wx_login()
def index(request):
    try:
        wx_obj = get_wx_session(request)
        wx_obj = WxUserInfo.objects.get(openid=wx_obj.openid)
        if wx_obj.salesman:
            logon = "true"
        else:
            logon = "false"
    except Exception as e:
        print(e)
        logon = 'false'
    host = Config.no_protocol
    # host = "//127.0.0.1:8002"
    context = {"logon": logon, "host": host}
    return render(request, "c2c/index.html", context)


@wx_login()
@verify_tel()
def register(request):
    # card = request.POST.get('card')
    account = request.POST.get("account")
    password = request.POST.get("password")
    name = request.POST.get("name")
    tel = request.POST.get("tel")
    wx_obj = get_wx_session(request)
    if account:
        # 增加账号内容
        try:
            password = md5(password)
            password = md5(password)
            sales_obj = SalesMan.objects.get(account=account, password=password)
            sales_obj.wx_user = wx_obj
            sales_obj.show_alert = False
            sales_obj.save()
            context = {"status": "ok", "msg": "成功"}
            return JsonResponse(context)
        except Exception as e:
            print(e)
            context = {"status": "error", "msg": "账号密码错误"}
            return JsonResponse(context)
    else:
        sales_obj, created = SalesMan.objects.get_or_create(
            tel=tel
        )
        try:
            relation_obj = BoundRelation.objects.get(openid=wx_obj.openid)
            leader_obj = relation_obj.t_user
        except Exception as e:
            print(e)
            leader_obj = SalesMan.objects.get(tel="13366542267")  # 这里需要个默认的上级，需要能打电话联系或加微信。
        # sales_obj.card = card
        sales_obj.name = name
        sales_obj.leader = leader_obj
        sales_obj.wx_user = wx_obj
        sales_obj.show_alert = False
        sales_obj.channel = leader_obj.channel
        if leader_obj.account == "yinlianshangwu":
            sales_obj.can_transfer = False
        sales_obj.save()
        # 加人数
        leader_obj.num = F("num") + 1
        leader_obj.save()
        context = {"status": "ok", "msg": "成功"}
        return JsonResponse(context)


@wx_login()
def team(request):
    """
    团队列表
    :param request:
    :return:
    """
    wx_obj = get_wx_session(request)
    user_info = wx_obj.salesman

    page = int(request.GET.get("page")) if request.GET.get("page") else 1
    lower_list = user_info.salesman_set.all()
    lower_list = lower_list.order_by("-num")
    lower_list, page_dict = DjangoPaginator.get_paging(lower_list, page_size=10, page=page)
    team_list = []
    for i in lower_list:
        d = dict()
        d["name"] = i.name if i.name else i.account
        d["count"] = i.salesman_set.count()
        d["talk"] = True if i.qr_code else False
        try:
            wx_obj = i.wx_user
            d["head_url"] = wx_obj.head_url
        except Exception as e:
            print(e)
        d["qr_code"] = Config.host + i.qr_code.url if d["talk"] else ""
        team_list.append(d)
    content = {"status": "ok", "team_list": team_list, "page_dict": page_dict}
    return JsonResponse(content)


@wx_login()
def leader_show(request):
    """
    专属客服
    :param request:
    :return:
    """
    wx_obj = get_wx_session(request)
    user_info = wx_obj.salesman
    leader = user_info.leader
    if leader:
        pass
    else:
        leader = SalesMan.objects.get(tel="13366542267")
    if leader.qr_code:
        qr_code = Config.host + leader.qr_code.url
        head_url = leader.wx_user.head_url
        name = leader.name
        tel = leader.tel
    else:
        base_sales = SalesMan.objects.get(tel="13366542267")
        qr_code = Config.host + base_sales.qr_code.url
        head_url = base_sales.wx_user.head_url
        name = base_sales.name
        tel = base_sales.tel
    content = {"head_url": head_url, "name": name, "tel": tel, "qr_code": qr_code}
    return JsonResponse(content)


@wx_login()
def team_income(request):
    """
    :param request:
    :return:
    """
    wx_obj = get_wx_session(request)
    user_info = wx_obj.salesman
    is_close = request.GET.get("is_close")
    product_id = request.GET.get('p_id')
    income = TeamInCome.objects.filter(salesman=user_info).exclude(income=0)
    if is_close:
        income = income.filter(is_close=is_close)
    if product_id and product_id != "0":
        product_obj = Product.objects.get(id=product_id)
        if product_obj.sign_type == 4:
            product_queryset = product_obj.product_set.all()
            income1 = income.filter(order__product__in=product_queryset)
            income2 = income.filter(order__product_id=product_id)
            income = income1 | income2
        else:
            income = income.filter(order__product_id=product_id)
    page = int(request.GET.get("page")) if request.GET.get("page") else 1
    income, page_dict = DjangoPaginator.get_paging(income, page=page)
    team_income_list = []
    for i in income:
        d = dict()
        if i.level == 2:  # 下下级
            d["name"] = i.order.salesman.leader.name
        if i.level == 1:  # 下级
            d["name"] = i.order.salesman.name
        d["is_close"] = i.order.product.name  # i.get_is_close_display()
        d["create_time"] = i.create_time.strftime("%Y-%m-%d")
        d["income"] = i.income
        team_income_list.append(d)
    content = {"status": "ok", "team_income_list": team_income_list, "page_dict": page_dict}
    return JsonResponse(content)


@wx_login()
def my_info(request):
    # app 需要获取数据
    # web 直接用session里的数据就行
    wx_obj = get_wx_session(request)
    # openid = wx_obj.openid
    # wx_obj = WxUserInfo.objects.get(openid=openid)
    user_info = wx_obj.salesman
    user_info.refresh_from_db()
    nick_name = user_info.wx_user.nick_name
    head_url = user_info.wx_user.head_url
    qr_code = user_info.qr_code
    if user_info.card:
        first = "false"
    else:
        first = "true"
    if qr_code:
        qr_code = Config.host + qr_code.url
    else:
        qr_code = ""
    if user_info.account and user_info.password:
        show_edit_pwd = True
    else:
        show_edit_pwd = False
    content = {
        "show_edit_pwd": show_edit_pwd,
        "nick_name": nick_name,
        "qr_code": qr_code,
        "head_url": head_url,
        "tel": user_info.tel,
        "name": user_info.name,
        "first": first,
        "card": user_info.card,
        "card_num": user_info.card_num,
        "show_declaration": user_info.channel.show_declaration  # 是否显示免责声明
    }
    return JsonResponse(content)


@wx_login()
def upload_qr_code(request):
    """
    上传微信二维码
    :param request:
    :return:
    """
    wx_obj = get_wx_session(request)
    user_info = wx_obj.salesman
    file_obj = request.FILES["qr_code"]
    if file_obj:
        try:
            last_name = file_obj.name.split('.')[1]
            file_name = datetime.datetime.now().strftime("%Y%m%d%H%M%S") + str(
                random.randint(1, 1000)) + '.' + last_name
            user_info.qr_code.save(file_name, file_obj)
            content = {"status": "ok", "msg": "上传成功", "url": Config.host + user_info.qr_code.url}
        except Exception as e:
            print(e)
            content = {"status": "error", "msg": "上传失败"}
    else:
        content = {"status": "error", "msg": "哎呦，没有发现文件"}
    return JsonResponse(content)


@wx_login()
def update_card_num(request):
    """
    更新卡号
    :param request:
    :return:
    """
    card_num = request.POST.get("card_num")
    wx_obj = get_wx_session(request)
    user_info = wx_obj.salesman
    user_info.refresh_from_db()
    user_info.card_num = card_num
    user_info.save()
    content = {"status": "ok", "msg": "更新成功"}
    return JsonResponse(content)


@wx_login()
def update_card(request):
    """
    更新身份证
    :param request:
    :return:
    """
    wx_obj = get_wx_session(request)
    card = request.POST.get("card")
    user_info = wx_obj.salesman
    user_info.refresh_from_db()
    user_info.card = card
    user_info.save()
    content = {"status": "ok", "msg": "更新成功"}
    return JsonResponse(content)


@wx_login()
@verify_tel()
def update_tel(request):
    """
    更新手机号
    :param request:
    :return:
    """
    tel = request.POST.get("tel")
    if SalesMan.objects.filter(tel=tel).exists():
        content = {"status": "error", "msg": "手机号已经存在"}
    else:
        wx_obj = get_wx_session(request)
        user_info = wx_obj.salesman
        user_info.refresh_from_db()
        user_info.tel = tel
        user_info.save()
        content = {"status": "ok", "msg": "更新成功"}
    return JsonResponse(content)


@wx_login()
def update_name(request):
    """
    更新姓名
    :param request:
    :return:
    """
    name = request.POST.get("name")
    wx_obj = get_wx_session(request)
    user_info = wx_obj.salesman
    user_info.refresh_from_db()
    user_info.name = name
    user_info.save()
    content = {"status": "ok", "msg": "更新成功"}
    return JsonResponse(content)


@wx_login()
def update_pwd(request):
    """
    更新姓名
    :param request:
    :return:
    """
    wx_obj = get_wx_session(request)
    user_info = wx_obj.salesman
    password = request.POST.get("password")
    if len(password) > 7:
        password = md5(password)
        password = md5(password)
        user_info.password = password
        user_info.save()
        content = {"status": "ok", "msg": "更新成功"}
    else:
        content = {"status": "error", "msg": "密码不能小于8位"}
    return JsonResponse(content)


@wx_login()
def build_team(request):
    wx_obj = get_wx_session(request)
    salesman = wx_obj.salesman
    from .tools import compare_level
    if compare_level(salesman):
        pass
    else:
        content = {"status": "error", "msg": "show dialog"}
        return JsonResponse(content)
    url = Config.host + "/mp/c2c_share?sid=%s" % wx_obj.salesman.pk
    content = {"status": "ok", "url": url}
    return JsonResponse(content)


@wx_login()
def leader_show_wx(request):
    wx_obj = get_wx_session(request)
    openid = wx_obj.openid
    try:
        relation_obj = BoundRelation.objects.get(openid=openid)
        salesman = relation_obj.t_user
        channel_name = salesman.channel.name
        content = {"name": salesman.name, "tel": salesman.tel, "status": "ok", "channel_name": channel_name}
    except Exception as e:
        print(e)
        leader = SalesMan.objects.get(tel="13366542267")
        channel_name = leader.channel.name
        content = {"name": leader.name, "tel": leader.tel, "status": "ok", "channel_name": channel_name}
        # msg = "“零号金融”是一个免费的会员转介绍银行金融产品分享平台！目前，您还不是会员。期盼您的早日加入！"
        # content = {"status": "error", "msg": msg}
    return JsonResponse(content)


@wx_login()
# @verify_tel()
def enter_apply_add(request):
    # 平台添加和分享添加共用一个接口
    # name = request.POST.get("name")
    age = request.POST.get("age")
    kilometer = request.POST.get("kilometer")
    city_id = request.POST.get("c_pk")
    car_card = request.POST.get("car_card")
    # tel = request.POST.get("tel")
    product_id = request.POST.get("p_pk")
    buy_cash = request.POST.get("buy_cash")
    wx_obj = get_wx_session(request)
    openid = wx_obj.openid
    wx_obj = WxUserInfo.objects.get(openid=openid)
    salesman = wx_obj.salesman
    # 如果此用户有身份证号
    if salesman.card:
        apply_obj, created = ApplicantList.objects.get_or_create(
            tel=salesman.tel,
            salesman=salesman,
            card=salesman.card,
            name=salesman.name
        )
    # 如果没有身份证号
    else:
        content = {"status": "error", "msg": "请先去‘我的’里更新身份证号"}
        return JsonResponse(content)
    single = Single.objects.create(
        product_id=product_id,
        applicant=apply_obj,
        t_user=salesman.leader,
        b_user=salesman
    )
    EnterApplyInfo.objects.create(
        product_id=product_id,
        kilometer=kilometer,
        city_id=city_id,
        car_card=car_card,
        age=age,
        single=single,
        buy_cash=buy_cash
    )
    content = {"msg": "提交成功，银行客户经理会尽快与您联系。", "status": "ok"}
    # except Exception as e:
    #     print(e)
    #     content = {"msg": "服务器异常", "status": "error"}
    return JsonResponse(content)


def share_index(request):
    return render(request, "c2c/share_index.html")


def news_list(request):
    content_info = IssueContent.objects.all().order_by("-create_time")
    issue_list = []
    for i in content_info:
        d = dict()
        d["create_time"] = i.create_time.strftime("%m.%d")
        d["num"] = i.num
        d["title"] = i.title
        d["logo"] = Config.host + i.logo.url
        d["pk"] = i.pk
        issue_list.append(d)
    content = {"issue_list": issue_list}
    return JsonResponse(content)


def click_news(request):
    try:
        news_pk = request.GET.get("n_pk")
        content_info = IssueContent.objects.get(pk=news_pk)
        content_info.num = F("num") + 1
        content_info.save()
        img_query = content_info.issueimg_set.all()
        img_list = []
        for i in img_query:
            img_list.append(Config.host + i.img.url)
        content = {"status": "ok", "img_list": img_list}
    except Exception as e:
        print(e)
        content = {"status": "error", "msg": "请检查网络"}
    return JsonResponse(content)


@wx_login()
def applicants(request):
    wx_obj = get_wx_session(request)
    info = wx_obj.salesman.applicantlist_set.filter(show_status=True)
    apply_list = []
    for i in info:
        d = dict()
        d["name"] = i.name
        d["card"] = i.card
        d["tel"] = i.tel
        d["a_pk"] = i.pk
        apply_list.append(d)
    content = {"apply_list": apply_list}
    return JsonResponse(content)


@wx_login()
def channel_menus(request):
    """
    渠道菜单 如果没有展示全部
    :param request:
    :return:
    """
    wx_obj = get_wx_session(request)
    salesman = wx_obj.salesman
    # salesman = SalesMan.objects.get(id=salesman.id)
    channel = salesman.channel
    check_menus = channel.check_menus
    banner_ad = channel.banner_ad
    if check_menus == 1:
        content = {"menu_list": Config.menus, "banner_ad": banner_ad}
        return JsonResponse(content)
    elif check_menus == 2:
        menus = salesman.channel.channelmenus_set.all()
        menu_list = []
        for i in menus:
            data = dict()
            data["name"] = i.name
            data["sign"] = i.sign
            menu_list.append(data)
        content = {"menu_list": menu_list, "banner_ad": banner_ad}
    else:
        from .tools import compare_level
        if compare_level(salesman):
            content = {"menu_list": Config.menus, "banner_ad": banner_ad}
            return JsonResponse(content)
        else:
            menus = salesman.channel.channelmenus_set.all()
            menu_list = []
            if menus:
                for i in menus:
                    data = dict()
                    data["name"] = i.name
                    data["sign"] = i.sign
                    menu_list.append(data)
            content = {"menu_list": menu_list, "banner_ad": banner_ad}
    return JsonResponse(content)


#
# @wx_login()
# @verify_tel()
# def applicant_add(request):
#     tel = request.POST.get("tel")
#     card = request.POST.get("card")
#     if not verify_card(card):
#         # 验证身份证号
#         content = {"msg": "请检查身份证号", "status": "error"}
#         return JsonResponse(content)
#     name = request.POST.get("name")
#     product_id = request.POST.get("p_pk")
#     wx_obj = get_wx_session(request)
#     salesman = wx_obj.salesman
#     product_obj = Product.objects.get(id=product_id)
#     apply_obj, created = ApplicantList.objects.get_or_create(
#         tel=tel,
#         salesman=wx_obj.salesman,
#     )
#     apply_obj.card = card
#     apply_obj.name = name
#     apply_obj.save()
#     if not created:
#         apply_obj.show_status = True
#         apply_obj.save()
#     if product_obj.product_set.all():
#         parent_product = "true"
#     else:
#         parent_product = "false"
#     if parent_product == "false":
#         # 不带子产品的
#         Single.objects.create(
#             product=product_obj,
#             applicant=apply_obj,
#             t_user=salesman.leader,
#             b_user=salesman
#         )
#         if product_obj.api_type == 2 and product_obj.sign_type == 2:
#             status, content = apply(product_obj, apply_obj)
#             if status:
#                 content = {"url": content.get("bank_url"), "status": "ok", "id": product_obj.id}
#             else:
#                 content = {"status": "error", "message": content.get("message")}
#         else:
#             content = {"url": product_obj.url, "status": "ok", "parent_product": parent_product, "id": product_obj.id}
#     else:
#         # 带子产品的 (思兮)
#         content = {"status": "ok", "parent_product": parent_product, "id": product_obj.id, "apply_id": apply_obj.id}
#     return JsonResponse(content)
#
#
# @wx_login()
# def applicant_click(request):
#     """
#     点击申请人列表
#     :param request:
#     :return:
#     """
#     wx_obj = get_wx_session(request)
#     salesman = wx_obj.salesman
#     product_id = request.POST.get("p_pk")
#     apply_id = request.POST.get("a_pk")
#     product_obj = Product.objects.get(id=product_id)
#     if product_obj.product_set.all():
#         parent_product = "true"
#     else:
#         parent_product = "false"
#     if parent_product == "false":
#         # 不带子产品的
#         Single.objects.create(
#             product=product_obj,
#             applicant_id=apply_id,
#             t_user=salesman.leader,
#             b_user=salesman
#         )
#         if product_obj.api_type == 2 and product_obj.sign_type == 2:
#             apply_obj = ApplicantList.objects.get(id=apply_id)
#             status, content = apply(product_obj, apply_obj)
#             if status:
#                 content = {"url": content.get("bank_url"), "status": "ok", "id": product_obj.id}
#             else:
#                 content = {"status": "error", "message": content.get("message")}
#         else:
#             content = {"url": product_obj.url, "status": "ok", "parent_product": parent_product, "id": product_obj.id}
#     else:
#         # 带子产品的 (思兮)
#         content = {"status": "ok", "parent_product": parent_product, "id": product_obj.id, "apply_id": apply_id}
#     return JsonResponse(content)
#
#
# @wx_login()
# def applicant_delete(request):
#     """
#     删除申请
#     :param request:
#     :return:
#     """
#     wx_obj = get_wx_session(request)
#     salesman = wx_obj.salesman
#
#     apply_id = request.POST.get("a_pk")
#     ApplicantList.objects.filter(pk=apply_id, salesman=salesman).update(show_status=False)
#     content = {"status": "ok", "msg": "删除成功"}
#     return JsonResponse(content)
#
#
# @verify_tel()
# def share_click(request):
#     """
#     单产品分享，提交申请人信息
#     :param request:
#     :return:
#     """
#     product_id = request.POST.get("p_pk")
#     sales_id = request.POST.get("s_pk")
#     name = request.POST.get("name")
#     tel = request.POST.get("tel")
#     card = request.POST.get("card")
#     # 获取业务员
#     try:
#         salesman = SalesMan.objects.get(pk=sales_id)
#     except Exception as e:
#         print(e)
#         salesman = SalesMan.objects.get(tel="13366542267")
#     # 验证身份证号
#     if not verify_card(card):
#         content = {"msg": "请检查身份证号", "status": "error"}
#         return JsonResponse(content)
#     # 添加申请人
#     apply_obj, created = ApplicantList.objects.get_or_create(
#         tel=tel,
#         salesman=salesman,
#     )
#     apply_obj.card = card
#     apply_obj.name = name
#     apply_obj.save()
#     # 点击产品记录关系
#     product_obj = Product.objects.get(id=product_id)
#     if product_obj.product_set.all():
#         parent_product = "true"
#     else:
#         parent_product = "false"
#     if parent_product == "false":
#         # 不带子产品的
#         Single.objects.create(
#             product=product_obj,
#             applicant=apply_obj,
#             t_user=salesman.leader,
#             b_user=salesman
#         )
#         if product_obj.api_type == 2 and product_obj.sign_type == 2:
#             status, content = apply(product_obj, apply_obj)
#             if status:
#                 content = {"url": content.get("bank_url"), "status": "ok", "id": product_obj.id}
#             else:
#                 content = {"status": "error", "message": content.get("message")}
#         else:
#             content = {"url": product_obj.url, "status": "ok", "parent_product": parent_product, "id": product_obj.id}
#     else:
#         # 带子产品的 (思兮)
#         content = {"status": "ok", "parent_product": parent_product, "id": product_obj.id, "apply_id": apply_obj.id}
#     return JsonResponse(content)
#
#
# def apply_index(request):
#     return render(request, "c2c/one_product_index.html")
#
#
# def card_loan(request):
#     host = Config.no_protocol
#     # host = "http://127.0.0.1:8002"
#     return render(request, "c2c/carloan.html", locals())
#
#
# @verify_tel()
# def enter_apply_add_one(request):
#     name = request.POST.get("name")
#     age = request.POST.get("age")
#     kilometer = request.POST.get("kilometer")
#     city_id = request.POST.get("c_pk")
#     car_card = request.POST.get("car_card")
#     tel = request.POST.get("tel")
#     product_id = request.POST.get("p_pk")
#     sales_id = request.POST.get("sid")
#     buy_cash = request.POST.get("buy_cash")
#     salesman = SalesMan.objects.get(id=sales_id)
#     apply_obj, created = ApplicantList.objects.get_or_create(
#         tel=tel,
#         salesman=salesman,
#     )
#     if created:
#         apply_obj.show_status = False
#     apply_obj.name = name
#     apply_obj.save()
#     single = Single.objects.create(
#         product_id=product_id,
#         applicant=apply_obj,
#         t_user=salesman.leader,
#         b_user=salesman
#     )
#     EnterApplyInfo.objects.create(
#         product_id=product_id,
#         kilometer=kilometer,
#         city_id=city_id,
#         car_card=car_card,
#         age=age,
#         single=single,
#         buy_cash=buy_cash,
#     )
#     content = {"msg": "提交成功，银行客户经理会尽快与您联系。", "status": "ok"}
#     # except Exception as e:
#     #     print(e)
#     #     content = {"msg": "服务器异常", "status": "error"}
#     return JsonResponse(content)


@authentication()
def child_data(request):
    start_time = request.GET.get("start_time")
    end_time = request.GET.get("end_time")
    salesman = request.salesman
    child_list = salesman.salesman_set.filter(account__isnull=False)
    page = int(request.GET.get("page")) if request.GET.get("page") else 1
    child_list, page_dict = DjangoPaginator.get_paging(child_list, page=page)
    child_data_list = []
    now_time = datetime.datetime.now()
    base_time = now_time + datetime.timedelta(days=15)
    for i in child_list:
        data = dict()
        data["lower_level_account"] = i.account
        single_data = i.single_b_user_set.all()
        order_data = i.baseorder_set.all()
        if not start_time and not end_time and base_time:
            single_data = single_data.filter(create_time__gte=base_time)
            order_data = order_data.filter(create_time__gte=base_time)
        else:
            if start_time:
                single_data = single_data.filter(create_time__gte=start_time)
                order_data = order_data.filter(create_time__gte=base_time)
            if end_time:
                single_data = single_data.filter(create_time__gte=start_time)
                order_data = order_data.filter(create_time__gte=base_time)
        visit_num = single_data.count()
        success_num = order_data.count()
        data["visit_num"] = visit_num
        data["success_num"] = success_num
        del page_dict['next_page']
        del page_dict['before_page']
        child_data_list.append(data)
    return JsonResponse({"message": "SUCCESS", "data": {"child_list": child_data_list, "page_dict": page_dict}})
